/**
 * Created by tanbingqin on 2019/12/03.
 */
import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import { Form, Select, Row, Col, message, Icon} from 'antd';
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service';
import 'styles/expense-reimbursement-control/expense-standard/travel-policy/value-rule.scss'

const Option = Select.Option;

class ValueRule extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true, //编辑状态时的loading
      valueRuleList: [],
      valueList: [], //值列表列表
      selectValueOIDList: [] //选中的值列表
    }
  }

  componentDidMount(){
    this.getValueList();
  }

  componentWillReceiveProps(nextProps) {}

  initEdit = (data) => {
    this.setState({loading: true});
    const {valueList} = this.state;
    let valueOIDs = [];
    valueList.map(oneValue => {
      valueOIDs.push(oneValue.customEnumerationOID);
    });
    let valueRuleList = [];
    if (data.customEnumerationDTOs && data.customEnumerationDTOs.length) {
      let getItemService = [];
      data.customEnumerationDTOs.map(customEnumerationDTO => {
        getItemService.push(travelPolicyService.getCustomEnumerationItems(customEnumerationDTO.customEnumerationOID));
      });
      Promise.all(getItemService).then(res => {
        this.setState({loading: false});
        data.customEnumerationDTOs.map((customEnumerationDTO, index) => {
          let oneRule = {
            value: '',
            valueItem: [],
            valueList: valueList,
            valueItemList: []
          };
          let valueItemIDs = [];
          if (res[index].data.values && res[index].data.values.length) {
            res[index].data.values.map(itemValue => {
              valueItemIDs.push(itemValue.id);
            });
          }
          if (valueOIDs.indexOf(customEnumerationDTO.customEnumerationOID) > -1) {
            oneRule.value = customEnumerationDTO.customEnumerationOID;
            oneRule.valueItemList = res[index].data.values;
            customEnumerationDTO.values.map(item => {
              if (valueItemIDs.indexOf(item.id) > -1) {
                oneRule.valueItem.push(item.id);
              }
            });
          }
          valueRuleList.push(oneRule);
        });
        this.setState({valueRuleList: valueRuleList}, () => {
          this.refreshSelectValue();
          this.props.onChange(valueRuleList);
        });
      });
    } else {
      this.setState({loading: false});
    }
  };

  getValueList = () => {
    const { levelCode } = this.props;
    let serviceName = levelCode === 'SET_OF_BOOK' ? 'getCustomEnumerationInTenant' : 'getCustomEnumeration';
    travelPolicyService[serviceName](0, 200).then((resp) => {
      if (resp.status === 200) {
        this.setState({valueList: resp.data}, () => {
          if (this.props.data) {
            this.initEdit(this.props.data);
          } else {
            this.setState({loading: false});
          }
        });
      }
    }).catch((e) => {
      if (e.response && e.response.data && e.response.data.message) {
        message.error(e.response.data.message);
      }
    });
  };

  //选择值列表
  handleSelectValue = (value, index) => {
    const {valueRuleList} = this.state;
    valueRuleList[index].value = value;
    valueRuleList[index].valueItem = [];
    valueRuleList[index].valueItemList = [];
    this.setState({valueRuleList: valueRuleList}, () => {
      this.refreshSelectValue();
      this.props.onChange(valueRuleList);
    });
    travelPolicyService.getCustomEnumerationItems(value).then((resp) => {
      if (resp.status === 200) {
        valueRuleList[index].valueItemList = resp.data.values;
        this.setState({valueRuleList: valueRuleList});
      }
    }).catch((e) => {
      if (e.response && e.response.data && e.response.data.message) {
        message.error(e.response.data.message);
      }
    });
  };

  //刷新已选中的值列表
  refreshSelectValue = () => {
    const {valueRuleList} = this.state;
    let selectValue = [];
    valueRuleList.map(item => {
      selectValue.push(item.value);
    });
    this.setState({selectValueOIDList: selectValue});
  };

  //选择值列表项
  handleSelectItemValue = (values, index) => {
    const {valueRuleList} = this.state;
    valueRuleList[index].valueItem = values;
    this.setState({valueRuleList: valueRuleList}, () => {
      this.props.onChange(valueRuleList);
    });
  };

  addRule = () => {
    const {valueRuleList, valueList} = this.state;
    let oneRule = {
      value: '',
      valueItem: [],
      valueList: valueList,
      valueItemList: []
    };
    valueRuleList.push(oneRule);
    this.setState({
      valueRuleList: valueRuleList
    });
  };

  removeRule = (index) => {
    const {valueRuleList} = this.state;
    valueRuleList.splice(index, 1);
    this.setState({
      valueRuleList: valueRuleList
    }, () => {
      this.refreshSelectValue();
      this.props.onChange(valueRuleList);
    });
  };

  render() {
    const { valueRuleList, valueList, selectValueOIDList, loading } = this.state;
    const { disabled } = this.props;
    return (
      <div className="travel-standard-value-rule">
        {valueRuleList.map((oneRule, index) => {
          return (
            <Row style={{marginBottom: 10}} key={index}>
              <Col span={6}>
                <Select showSearch placeholder={messages('common.select')/*请选择*/}
                        value={oneRule.value ? oneRule.value : undefined}
                        disabled={disabled}
                        onChange={(value) => this.handleSelectValue(value, index)} optionFilterProp="children"
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {oneRule.valueList.map(item=><Option disabled={item.customEnumerationOID !== oneRule.value && selectValueOIDList.indexOf(item.customEnumerationOID) !== -1}
                                                       value={item.customEnumerationOID}
                                                       key={item.customEnumerationOID}>{item.name}</Option>)}
                </Select>
              </Col>
              <Col span={4} offset={1}>
                <Select defaultValue="contain" disabled>
                  <Option value="contain">{messages('request-1.key787')/*包含*/}</Option>
                </Select>
              </Col>
              <Col span={8} offset={1} className="multi-select">
                <Select showSearch mode="multiple" placeholder={messages('common.select')/*请选择*/}
                        disabled={!oneRule.valueItemList.length || disabled}
                        value={oneRule.valueItem.length ? oneRule.valueItem : undefined}
                        onChange={(values) => this.handleSelectItemValue(values, index)} optionFilterProp="children"
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                        filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                >
                  {oneRule.valueItemList.map(item=><Option value={item.id} key={item.id}>{item.messageKey}</Option>)}
                </Select>
              </Col>
              {!disabled && (
                <Col span={2}>
                  <Icon onClick={() => this.removeRule(index)} type="close-circle-o" style={{fontSize: 20, cursor: 'pointer'}}/>
                </Col>
              )}
            </Row>
          )
        })}
        {disabled && (
          <Row>
            <Col span={21}>
              <div className="add-rule-btn-disabled">
                +{messages('request-1.key788')/*添加条件*/}
              </div>
              <span style={{color: '#989898'}}>{messages('request-1.key789')/*条件与单据上的值列表匹配，条件间为and关系*/}</span>
            </Col>
          </Row>
        )}
        {!!valueList.length && valueRuleList.length < 3 && !loading && !disabled && (
          <Row>
            <Col span={21}>
              <div className="add-rule-btn" onClick={this.addRule}>
                +{messages('request-1.key788')/*添加条件*/}
              </div>
              <span style={{color: '#989898'}}>{messages('request-1.key789')/*条件与单据上的值列表匹配，条件间为and关系*/}</span>
            </Col>
          </Row>
        )}
        {(!valueList.length || loading) && (
          <Row>
            <Col span={21}>
              <Icon type="loading" style={{fontSize: 20}}/>
            </Col>
          </Row>
        )}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {

  }
}

ValueRule.propTypes = {
  levelCode: React.PropTypes.string,
  disabled: React.PropTypes.bool,
  onChange: React.PropTypes.func  //更改属性时的回调
};

ValueRule.defaultProps = {
  levelCode: '',
  disabled: false
};

const WrappedValueRule = Form.create()(ValueRule);

export default connect(mapStateToProps)(WrappedValueRule);
